/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.star.admin.controller;

import com.star.common.ActionType;
import com.star.common.CommonUtil;
import com.star.common.ConfigFactory;
import com.star.common.CrawlerNewsData;
import com.star.common.NewsCateData;
import com.star.common.PostData;
import com.star.common.ProfileData;
import com.star.common.Re_Post_NewsCate_Data;
import com.star.common.Re_Post_Profile_Data;
import com.star.common.RenderModel;
import com.star.common.UserRole;
import com.start.model.ActionModel;
import com.start.model.CrawlerNewsModel;
import com.start.model.NewsCateModel;
import com.start.model.PostModel;
import com.start.model.ProfileModel;
import com.start.model.Re_Post_NewsCate_Model;
import com.start.model.Re_Post_Profile_Model;
import com.start.model.SessionModel;
import com.sun.javafx.iio.ImageLoader;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javaxt.io.Image;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class AdminCrawlerNewsController extends HttpServlet{
    private static final Logger logger = Logger.getLogger(AdminCrawlerNewsController.class);
    private static final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    private static final int C_NEWS_PER_PAGE = 20;    
    public static final String STATIC_UPLOAD_IMAGE = ConfigFactory.getParam("upload", "upload_path") + ConfigFactory.getParam("upload", "upload_image");
    public static final String STATIC_UPLOAD_VIDEO = ConfigFactory.getParam("upload", "upload_path") + ConfigFactory.getParam("upload", "upload_video");
    public static final String STATIC_URL_IMAGE = ConfigFactory.getParam("static", "img") + ConfigFactory.getParam("upload", "upload_image");
    public static final String STATIC_URL_VIDEO = ConfigFactory.getParam("static", "img") + ConfigFactory.getParam("upload", "upload_video");
    private static final int BUFFER_SIZE = 4096;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }
    
    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminCrawlerNewsController.handle:" + ex.getMessage(), ex);
        }
    }
    
    
    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) { 
            case "/ajax-edit":
                content = ajaxEdit(req, resp);
                break;
            case "/ajax-delete":
                content = ajaxDelete(req, resp);
                break;
            case "/ajax-upload-image":
                content = ajaxUploadImage(req, resp);
                break;
            case "/ajax-upload-video":
                content = ajaxUploadVideo(req, resp);
                break;    
            case "/edit":
                content = renderEditPage(req, resp);
                break;
            case "/search":
                content = renderSearchPage(req, resp);
                break;
            case "/list":
                content = renderIndexPage(req, resp);
                break;
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }
    
    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.C_NEWS_EDIT)) {
                resp.sendRedirect("/");
                return "";
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req)); 
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "c_news"));            
            dic.setVariable("PAGE_TITLE", "Danh sách tin tức");
                        
            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }
                        
            CrawlerNewsModel c_NewsModel = CrawlerNewsModel.getInstance();
            List<CrawlerNewsData> lstC_NewsData = c_NewsModel.getC_News((page - 1) * C_NEWS_PER_PAGE, C_NEWS_PER_PAGE);              
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            if (lstC_NewsData != null && !lstC_NewsData.isEmpty()) {
                for (CrawlerNewsData c_NewsData : lstC_NewsData) {                    
                    TemplateDataDictionary section = dic.addSection("LIST_C_NEWS");   
                    section.setVariable("SOURCE_NEWS", c_NewsData.getSite());  
                    section.setVariable("C_NEWS_ID", c_NewsData.getId());  
                    section.setVariable("C_NEWS_TITLE", c_NewsData.getTitle());                       
                    Date d = new Date(c_NewsData.getPublished() * 1000);
                    section.setVariable("CREATED", sdf.format(d));
                    //section.setVariable("DESC_C_NEWS", c_NewsData.getDesc().substring(0, c_NewsData.getDesc().length() > 70 ? 70 : c_NewsData.getDesc().length()) + "...");
                    section.setVariable("URL_NEWS", c_NewsData.getUrl()); 
                    section.setVariable("URL_VIEW", c_NewsData.getUrl().substring(0, c_NewsData.getUrl().length() > 50 ? 50 : c_NewsData.getUrl().length()) + "...");
                }
            }
             
            int count = c_NewsModel.getC_News(0, -1).size();
            String pageNavi = CommonUtil.getPageNavi(page, count, C_NEWS_PER_PAGE, "");
            dic.setVariable("PAGENAVI", pageNavi);
                        
            Template template = RenderModel.getAdminCTemplate("c_news_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminCrawlerNewsController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    
    private String renderSearchPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.C_NEWS_EDIT)) {
                return CommonUtil.toPermissionDenied();
            }
            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req)); 
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "c_news"));            
            dic.setVariable("PAGE_TITLE", "Danh sách tin tức");
                        
            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }
            
            String id_Search = req.getParameter("postID") != null ? req.getParameter("postID") : "";
            String source_Se = req.getParameter("postSource") != null ? req.getParameter("postSource") : "";
            String title = req.getParameter("postTitle") != null ? req.getParameter("postTitle") : "";            
            String published = req.getParameter("postCreated") != null ? req.getParameter("postCreated") : "";             
                  
            CrawlerNewsModel c_NewsModel = CrawlerNewsModel.getInstance();
            List<CrawlerNewsData> lstC_NewsData = c_NewsModel.getC_News(0, -1, title, id_Search, published, source_Se);            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            if (lstC_NewsData != null && !lstC_NewsData.isEmpty()) {                
                for(int i = (page - 1) * C_NEWS_PER_PAGE; i < page * C_NEWS_PER_PAGE; i++){ 
                    if(i == lstC_NewsData.size())
                        break;
                    CrawlerNewsData c_NewsData = lstC_NewsData.get(i); 
                    TemplateDataDictionary section = dic.addSection("LIST_C_NEWS");   
                    section.setVariable("SOURCE_NEWS", c_NewsData.getSite());  
                    section.setVariable("C_NEWS_ID", c_NewsData.getId());  
                    section.setVariable("C_NEWS_TITLE", c_NewsData.getTitle());                       
                    Date d = new Date(c_NewsData.getPublished() * 1000);
                    section.setVariable("CREATED", sdf.format(d));                    
                    //section.setVariable("DESC_C_NEWS", c_NewsData.getDesc().substring(0, c_NewsData.getDesc().length() > 70 ? 70 : c_NewsData.getDesc().length()) + "...");
                    section.setVariable("URL_NEWS", c_NewsData.getUrl()); 
                    section.setVariable("URL_VIEW", c_NewsData.getUrl().substring(0, c_NewsData.getUrl().length() > 50 ? 50 : c_NewsData.getUrl().length()) + "...");
                }
            }
                        
            dic.setVariable("ID_SEARCH", id_Search);
            dic.setVariable("SOURCE_SEARCH", source_Se);
            dic.setVariable("TITLE_SEARCH", title);            
            dic.setVariable("CREATE_SEARCH", published); 
            
            int count = lstC_NewsData.size();
            String pageNavi = CommonUtil.getPageNavi(page, count, C_NEWS_PER_PAGE, "?" + req.getQueryString());
            dic.setVariable("PAGENAVI", pageNavi);
            
            Template template = RenderModel.getAdminCTemplate("c_news_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminCrawlerNewsController.renderSearchPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    private String renderEditPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.C_NEWS_EDIT)) {
                return CommonUtil.toPermissionDenied();
            }
            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "c_news"));
            dic.setVariable("PAGE_TITLE", "Duyệt tin tức");
                        
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.isEmpty()) {
                resp.sendRedirect("/crawler");
                return "";
            }       
            ProfileModel profileModel = ProfileModel.getInstance();
            dic.setVariable("PROFILE_LIST", profileModel.getProfileList());
            CrawlerNewsModel c_NewsModel = CrawlerNewsModel.getInstance();
            CrawlerNewsData c_NewsData = c_NewsModel.getC_NewsById(id);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            if (c_NewsData != null) {                
                dic.setVariable("NEWS_ID", c_NewsData.getId());
                dic.setVariable("IMAGES_CONTENT", c_NewsData.getImages());
                dic.setVariable("NEWS_TAGS", c_NewsData.getTags());
                dic.setVariable("NEWS_AUTHOR", c_NewsData.getAuthor());                
                dic.setVariable("NEWS_TITLE", c_NewsData.getTitle());
                dic.setVariable("NEWS_SOURCE", c_NewsData.getSite());
                dic.setVariable("URL_NEWS", c_NewsData.getUrl()); 
                Date d = new Date(c_NewsData.getPublished() * 1000);
                String time = sdf.format(d);
                dic.setVariable("NEWS_TIME", time);
                String image = c_NewsData.getThumbFb();
                if (image.isEmpty()) {
                    dic.showSection("NO_THUMB");
                } else {
                    dic.showSection("HAS_THUMB");                    
                    dic.setVariable("IMAGE_SRC", image);                                   
                    dic.setVariable("IMAGE_NAME", image);
                }                
                
                NewsCateModel newsCateModel = NewsCateModel.getInstance();
                List<NewsCateData> listNewsCate = newsCateModel.getCate(0, -1);
                if (listNewsCate != null && !listNewsCate.isEmpty()) {                    
                    for (NewsCateData cateData : listNewsCate) {
                        TemplateDataDictionary section = dic.addSection("NEWSCATE_LIST");
                        section.setVariable("NEWSCATE_ID", String.valueOf(cateData.getId()));
                        section.setVariable("NEWSCATE_NAME", cateData.getName());                        
                    }
                }                
                dic.setVariable("NEWS_DESC", c_NewsData.getDesc());
                dic.setVariable("NEWS_CONTENT", c_NewsData.getContent());
                      
                Template template = RenderModel.getAdminCTemplate("c_news_edit");
                content = template.renderToString(dic);
            } else {
                resp.sendRedirect("/crawler");
                return "";
            }
        } catch (Exception ex) {
            logger.error("AdminCrawlerNewsController.renderEditPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    private String ajaxEdit(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.C_NEWS_EDIT)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Duyệt tin tức thành công.";
        Map<String, String> data = new HashMap<>();
        try {
            String newsId = "";
            String imagesContent = "";
            String tags = "";
            String authorNews = "";
            String title = "";
            String slug = CommonUtil.URLFriendly(title);
            String site = "";            
            long published = 0;
            String image = "";
            String thumbFb = "";
            List<String> lstCats = new ArrayList<>();
            String desc = "";
            List<String> lstProfile = new ArrayList<>();
            String scontent = "";
            String status = "0";                             
            FileItem fileImage = null;

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator(); 
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String name = item.getFieldName();
                if (item.isFormField()) {
                    String value = item.getString("UTF-8");
                    switch (name) {
                        case "newsId":
                            newsId = value;
                            break;  
                        case "imagesContent":
                            imagesContent = value;
                            break;
                        case "tagsNews":
                            tags = value;
                            break;  
                        case "authorNews":
                            authorNews = value;
                            break;                             
                        case "newsTitle":
                            title = value;
                            break;
                        case "newsSource":
                            site = value;
                            break;     
                        case "newsTime":
                            if (!value.isEmpty()) {
                                if(value.length() == 10)
                                    value = value + " 00:00";
                                Date date = sdf.parse(value);
                                published = date.getTime();
                            }
                            else
                                published = System.currentTimeMillis();
                            break;
                        case "imageOld":
                            thumbFb = value;
                            break;
                        case "newsCate":
                            lstCats.add(value);
                            break;  
                        case "newsDesc":
                            desc = value;
                            break;
                        case "postListProfile":
                            lstProfile = Arrays.asList(value.split("\\s*,\\s*"));
                            break;    
                        case "newsContent":
                            scontent = value;
                            break;             
                    }
                } 
                else {
                    if (name.equalsIgnoreCase("newsImage")) {
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        if (!contentType.startsWith("image/")) {
                            msg = "Chỉ được phép upload hình jpg, png, gif.";
                            error = -1;
                        }
                        long sizeInBytes = item.getSize();
                        if (sizeInBytes > 1024 * 1000) {
                            msg = "Kích thước tối đa 1 MB.";
                            error = -1;
                        }
                        image = System.currentTimeMillis() + "_" + fileName.toLowerCase();
                        image = image.substring(0, image.length() - 4) + ".jpg";
                        fileImage = item;
                    }
                }
            }
            if (title.equalsIgnoreCase("")) {
                msg = "Tiêu đề tin tức không được trống.";
                error = -1;
            }
            if(lstCats.isEmpty()){
                msg = "Chưa chọn danh mục.";
                error = -1;
            }
            
            if (error == 0) {                
                SessionModel sessionModel = SessionModel.getInstance();                
                String author = sessionModel.getUserLogin(req);                
                PostModel postModel = PostModel.getInstance();                
                Date dateNow = new Date(); 
                String timeDir = (dateNow.getYear() + 1900) + "_" + (dateNow.getMonth() + 1);
                List<String> lstImageContent = Arrays.asList(imagesContent.split("\\s*,\\s*"));
                for(String item : lstImageContent){
                    String fileNameImage = download(item, STATIC_URL_IMAGE.substring(1) + timeDir + "/");
                    scontent = scontent.replace(item, ".." + STATIC_URL_IMAGE + timeDir + "/" + fileNameImage);                    
                }
                //image = fileImage == null ? thumbFb : image;
                String imageSaveName = "";
                if(fileImage != null){                    
                    saveThumb(fileImage, image, timeDir);
                    imageSaveName = image;
                }
                else{
                    imageSaveName = download(thumbFb, STATIC_URL_IMAGE.substring(1) + timeDir + "/");                    
                }
                PostData postData = new PostData(title, slug, desc, scontent, 
                                author, Short.parseShort(status), published, site, imageSaveName, tags, authorNews);
                String postId = postModel.addNewPost(postData); 
                if (!postId.isEmpty()) {
                    Re_Post_NewsCate_Model modelRePostCate = Re_Post_NewsCate_Model.getInstance();
                    for (String cate : lstCats) {
                        Re_Post_NewsCate_Data dataRe = new Re_Post_NewsCate_Data(postId, cate);                        
                        modelRePostCate.addItems(dataRe);
                    }
                    
                    ProfileModel profileModel = ProfileModel.getInstance();
                    Re_Post_Profile_Model modelRe = Re_Post_Profile_Model.getInstance();
                    for(String idProfile : lstProfile){
                        if(!idProfile.equals("")){
                            ProfileData profileData = profileModel.getProfileById(idProfile);
                            if(profileData != null){
                                Re_Post_Profile_Data dataRe = new Re_Post_Profile_Data(postId, idProfile);                            
                                modelRe.addItems(dataRe);
                            }                            
                        }                        
                    }                 
                    
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, author, ActionType.C_NEWS_ADD, postId, title);                                        
                }                                                
                 //delete from crawler                               
                CrawlerNewsModel c_NewsModel = CrawlerNewsModel.getInstance();                               
                c_NewsModel.deleteC_News(newsId);   
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }
    
    
    private String ajaxDelete(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.C_NEWS_EDIT)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Xoá tin tức thành công.";
        try {
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.isEmpty()) {
                msg = "Id tin tức không được trống.";
                error = -1;
            } else {
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);                
                CrawlerNewsModel c_NewsModel = CrawlerNewsModel.getInstance();
                CrawlerNewsData newsData = c_NewsModel.getC_NewsById(id);
                String title = newsData.getTitle();
                boolean addApps = c_NewsModel.deleteC_News(id);                
                if (!addApps) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{                                       
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.C_NEWS_DELETE, id, title);
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg);
        return content;
    }  
    
    
    
    public static String download(String fileURL, String saveDir) {
        try {
            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();

            // always check HTTP response code first
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String fileName = "";
                String disposition = httpConn.getHeaderField("Content-Disposition");
                String contentType = httpConn.getContentType();
                int contentLength = httpConn.getContentLength();

                String realURL = httpConn.getURL().toString();
                
                if (disposition != null) {
                    // extracts file name from header field
                    int index = disposition.indexOf("filename=");
                    if (index > 0) {
                        fileName = disposition.substring(index + 10,
                                disposition.length() - 1);
                    }
                }
                else {
                    // extracts file name from URL
                    fileName = realURL.substring(realURL.lastIndexOf("/") + 1,
                            realURL.length());
                }
                if(fileName.isEmpty() || fileName.contains("?")){
                    fileName = fileName.replace(fileName.substring(fileName.lastIndexOf("?")),"");
                }
                String ext = getExtensionfromContentType(contentType);
                String currExt = FilenameUtils.getExtension(fileName);
                if(ext!=null && !ext.isEmpty() && (currExt==null || !currExt.equals(ext))){
                    fileName = fileName + "." + ext;
                }

                logger.info("Content-Type = " + contentType);
                logger.info("Content-Disposition = " + disposition);
                logger.info("Content-Length = " + contentLength);
                logger.info("fileName = " + fileName);

                // opens input stream from the HTTP connection
                InputStream inputStream = httpConn.getInputStream();
                             
                fileName = System.currentTimeMillis() + "_" + fileName;
                String saveFilePath = saveDir + fileName;
                //String nameBefore = saveFilePath;
                saveFilePath = generateFileNameIfDuplicate(saveFilePath);
                //String nameAfter = saveFilePath;
                fileName = saveFilePath.substring(saveFilePath.lastIndexOf("/") + 1);
                File file  = new File(saveFilePath);
                file.getParentFile().mkdirs();
                // opens an output stream to save into file
                FileOutputStream outputStream = new FileOutputStream(file);
                logger.info("filePath = " + saveFilePath);
                int bytesRead = -1;
                byte[] buffer = new byte[BUFFER_SIZE];
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                
                outputStream.close();
                inputStream.close();
                logger.info("File downloaded");
                return fileName;
            } else {
                logger.error("No file to download. Server replied HTTP code: " + responseCode);
            }
            httpConn.disconnect();
        } catch (MalformedURLException ex) {
            logger.error("DownloadAnyFile: MalformedURLException" + ex + ex.getMessage());
        } catch (FileNotFoundException ex) {
            logger.error("DownloadAnyFile: FileNotFoundException" + ex + ex.getMessage());
            ex.printStackTrace();
        } catch (IOException ex) {
            logger.error("DownloadAnyFile: IOException" + ex + ex.getMessage());
        }
        return null;
    }
    
    
    
    public static String getExtensionfromContentType(String contentType) {
        String extension = "";
        switch (contentType) {
            case "image/jpeg":
                extension = "jpg";
                break;
            case "image/png":
                extension = "png";
                break;
        }
        return extension;
    }
    
    
    public static String generateFileNameIfDuplicate(String org){
        File f = new File(org);
        if(!f.exists() || f.isDirectory()){
            return org;
        }
        String res = org;
        String ext = FilenameUtils.getExtension(org);
        String bef = org.substring(0, org.lastIndexOf(ext)-1);
        int index = 0;
        while(f.exists() && !f.isDirectory()){
            index++;
            res = bef + "(" + index + ")." + ext;
            f = new File(res);
        }
        return res;
    }
    
        
    private void saveThumb(FileItem fileImage, String image_pa, String timeDir) throws Exception {
        if (fileImage != null) {
            Image image = new Image(fileImage.get());
            image.resize(250, 250);
            int w = image.getWidth() > 250 ? 250 : image.getWidth();
            int h = image.getHeight() > 250 ? 250 : image.getHeight();
            image.crop(0, 0, w, h);

            BufferedImage bi = CommonUtil.convertPNGToJPG(image.getBufferedImage());
            String localPath = STATIC_UPLOAD_IMAGE + timeDir + "/" + image_pa;
            File uploadedFile = new File(localPath);
            uploadedFile.getParentFile().mkdirs();
            ImageIO.write(bi, "jpg", uploadedFile);
        }
    }
    
    
        
    private String ajaxUploadImage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        int error = 0;
        String msg = "Upload hình thành công.";
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equalsIgnoreCase("postImage")) {
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        if (!contentType.startsWith("image/")) {
                            msg = "Chỉ được phép upload hình jpg, png, gif.";
                            error = -1;
                        }
                        long sizeInBytes = item.getSize();
                        if (sizeInBytes > 1024 * 1000) {
                            msg = "Kích thước tối đa 1 MB.";
                            error = -1;
                        }
                        String postImage = (System.currentTimeMillis() / 1000) + "_" + fileName.toLowerCase();
                        // crop and resize
                        if (item != null) {
                            Image image = new Image(item.get());
                            BufferedImage bi = image.getBufferedImage();
                            if (!postImage.endsWith(".jpg")) {
                                bi = CommonUtil.convertPNGToJPG(bi);
                            }
                            String localPath = STATIC_UPLOAD_IMAGE + postImage;
                            //String remotePath = REMOTE_POST_PATH + postImage;
                            File uploadedFile = new File(localPath);
                            ImageIO.write(bi, "jpg", uploadedFile);
                            // put to FTP 
                            //CommonUtil.putImageToFTP(localPath, remotePath);
                            postImage = STATIC_URL_IMAGE + postImage;
                            content = "<script>top.$('.mce-btn.mce-open').parent().find('.mce-textbox').val('" + postImage + "').closest('.mce-window').find('.mce-primary').click();</script>";
                        }
                    }
                }
            }
            if (error == 0) {

            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
//        content = CommonModel.toJSON(error, msg, data);
        return content;
    }
    
    
    private String ajaxUploadVideo(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        int error = 0;
        String msg = "Upload video thành công.";
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equalsIgnoreCase("postVideo")) {
                        String fileName = item.getName();
                        fileName = fileName.replace(" ", "-");
                        String postVideo = (System.currentTimeMillis() / 1000) + "_" + fileName.toLowerCase();
                        // crop and resize
                        if (item != null) {
                            String localPath = STATIC_UPLOAD_VIDEO + postVideo;
                            //String remotePath = REMOTE_VIDEO_PATH + postVideo;
                            File uploadedFile = new File(localPath);
                            item.write(uploadedFile);
                            
                            // put to FTP 
                            //CommonUtil.putImageToFTP(localPath, remotePath);
                            postVideo = STATIC_URL_VIDEO + postVideo;
                            content = "<script>top.$('.mce-btn.mce-open').parent().find('.mce-textbox').val('" + postVideo + "')/*.closest('.mce-window').find('.mce-primary').click()*/;</script>";
                        }
                    }
                }
            }
            if (error == 0) {

            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
//        content = CommonModel.toJSON(error, msg, data);
        return content;
    }
    
}
